/**
 * 健康数据
 * Created by KB on 16/8/19.
 */

import {health} from "../const/health";
import PullRefresh from '../components/mui/PullRefresh.js';
import NoData from "../components/NoData";

const lf = liefeng,
    R = React,
    RC = React.createClass,
    ajax = lf.utils.ajax,
    api = health.api,
    doAction = lf.bridgeJs.doAction,
    apiUrl = api.prefix;

const itemIcon = [
    {
        type: health.type.blood, //血压
        text: '血压',
        iconType: 'al-icon',
        icon: 'icon-xieya',
    },
    {
        type: health.type.temperature, //体温
        text: '体温',
        iconType: 'al-icon',
        icon: 'icon-baowen01',
    },
    {
        type: health.type.weight, //体重
        text: '体重',
        iconType: 'al-icon',
        icon: 'icon-icontz',
    },
    {
        type: health.type.fat, //脂肪
        text: '脂肪',
        iconType: 'al-icon',
        icon: 'icon-zhifang',
    }
]

const Item = RC({
    render(){
        let items = this.props.data.detectItemResults.map((data, index) => {
            
            return (
                <ItemIcon key={index} data={data} userId={this.props.data.userId} name={this.props.data.name}/>
            )
        });
        return (
            <div className="order-query-items flex border-bottom">
                {items}
            </div>
        )
    }
})

const ItemIcon = RC({
    componentDidMount(){
        let $item = React.findDOMNode(this.refs.item),
            props = this.props;
        
        $($item).on('tap', ()=> {
            doAction("finger-data-analysis.html?&userId=" + props.userId + '&type=' + props.data.type)
        })
    },
    render(){
        let data = this.props.data,
            type = data.type,
            iconInfo = [''],
            result = data.result == 'NORMAL' ? '' : 'un-normal';
        
        for (let i = 0; i < itemIcon.length; i++) {
            if (type == itemIcon[i].type) {
                iconInfo = itemIcon[i];
                break;
            }
        }
        return (
            <a href="javascript:;" className={"flex-item flex col " + result} ref="item">
                <i className={iconInfo.iconType + ' ' + iconInfo.icon}/>
                <span className="text">{iconInfo.text}</span>
            </a>
        )
    }
})

const ListTitle = RC({
    componentDidMount(){
        let $more = React.findDOMNode(this.refs.more),
            updateUser = this.props.updateUser, //用于新用户的,只有一个人
            data = this.props.data; //动态获取userid
        
        $($more).on('tap', ()=> {
            doAction('finger-love-care.html?userId=' + data.userId || updateUser.id, '亲情关怀');
        })
    },
    render(){
        let data = this.props.data,
            user = this.props.user;
        return (
            <div className={"mui-table-view-cell title" + ''}>
                <span className="text">{data.name}</span>
                {
                    data.name == user.name ? null : <a className="more" href="javascript:;" ref="more">亲情关怀</a>
                }
            </div>
        )
    }
})


const Root = RC({
    getInitialState(){
        return ({
            data: [],
            hasList: '',
            updateUser: {},
        })
    },
    
    componentWillMount(){
        var me = this,
            user = me.props.user;
        if (user.userId) {
            me.getHouserInfo(user);
        } else {
            ajax({
                type: "POST",
                data: {
                    phone: user.mobile || (user.custLoginVo && user.custLoginVo.mobile),
                },
                success: function (data) {
                    if (data.code == '200') {
                        var updateUser = data.data;
                        try {
                            me.setState({
                                updateUser: updateUser,
                                hasList: !updateUser ? 'no' : '',
                            })
                            updateUser ? me.queryMembersDetectResult(updateUser.id, true) : null;
                        } catch (e) {
                            console.log(e);
                        }
                    } else {
                        alert(data.desc);
                    }
                }
            }, lf.finger.api.user.getUserByPhone);
        }
    },
    //获取houseNum
    getHouserInfo(user){
        ajax({
            type: "get",
            data: {
                houseId: user.houseId || this.props.user.houseId
            },
        }, lf.finger.api.household.getHouseInfo, (data) => {
            //成功
            this.loadFamily(data.houseNum);
        });
    },
    //获取familyId
    loadFamily(houseNum){
        ajax({
            type: "get",
            url: apiUrl + api.loadFamily,
            data: {
                houseNum: houseNum,
                projectId: this.props.user.projectId,
            }
        }, null, (data) => {
            if (!data) {
                this.setState({
                    hasList: 'no',
                })
            } else {
                this.queryMembersDetectResult(data.id);
            }
        });
    },
    //获取列表
    queryMembersDetectResult(familyId, newUser){
        if (newUser) {
            ajax({
                type: 'get',
                url: apiUrl + api.queryUserDetectResult,
                data: {
                    userId: familyId,//todo this is the userId,only in new user's info
                },
            }, null, (data) => {
                this.setState({
                    data: data,
                    hasList: data ? 'more' : 'no',
                })
            })
        } else {
            ajax({
                type: 'get',
                url: apiUrl + api.queryMembersDetectResult,
                data: {
                    familyId: familyId,
                },
            }, null, (data) => {
                this.setState({
                    data: data,
                    hasList: data && data.length ? 'more' : 'no',
                })
            })
        }
    },
    
    render(){
        let list = this.state.hasList == 'no' ? <NoData data={{span_text:'还没有健康数据哦~'}}/> :
            this.state.data.map(data => {
                return (
                    <div className="list">
                        <ListTitle data={data} user={this.props.user} updateUser={this.state.updateUser}/>
                        <Item data={data}/>
                    </div>
                )
            })
        return (
            <div className="healthy-data">{list}</div>
        )
    }
})


lf.appJs.getUser(function (user) {
    console.log(user)
    R.render(
        <PullRefresh data={ <Root user={user}/>}/>,
        document.getElementById('root'), function () {
            $('.mui-scroll').css('background-color', '#ededed');
        }
    );
});
